package com.globallogic.training.javase.basics;

import java.util.Scanner;

/**
* The console application finding prime numbers
* smaller or equal to the provided integer number.
* 
* @version 1.4
* @author Artem.Zeltinsh 
*/
public class PrimeNumbersFinder 
{
	private static final String WELCOME_MESSAGE
			= "# This is the console application finding prime numbers\n"
			+ "#  smaller or equal to the provided integer number.\n";

	private static final String PROMPT_MESSAGE = "Please enter an integer number [2, " + Integer.MAX_VALUE + "]: ";
	
	private static final String OUTPUT_MESSAGE_FORMAT = "Found the following prime numbers: [%s]";
	
	private static final String OUTPUT_MESSAGE_DELIMITER = ", ";
	
	public static void main(String[] args) {
    	int boundaryNumber = readBoundaryNumber();

    	int[] primes = new int[boundaryNumber];
    	int primeCount = 0;
    	
    	for (int testNumber = 2; testNumber <= boundaryNumber; testNumber++) {
    		if(isPrime(testNumber)) {
    			primes[primeCount++] = testNumber;
    		}
        }
    	
        print(primes, 0, primeCount);
    }

	private static int readBoundaryNumber() {
		Scanner in = new Scanner(System.in);
    	System.out.println(WELCOME_MESSAGE);

    	int result = 0;
    	do {
        	System.out.print(PROMPT_MESSAGE);    		
        	result = in.nextInt();   
    	}
    	while (result < 2 || result > Integer.MAX_VALUE);
  
		return result;
	}
	
	private static boolean isPrime(int number) {
		for (int count = 2; count <= (int) Math.sqrt(number); count++) {
			if (number % count == 0) {
				return false;
			}
		}
		return true;
	}

	private static void print(int[] array, int startIndex, int endIndex) {
		StringBuilder outputMessage = new StringBuilder();
		
		for (int i = startIndex; i < endIndex; i++) {
			if (i != startIndex) {
				outputMessage.append(OUTPUT_MESSAGE_DELIMITER);
			}
			outputMessage.append(array[i]);
		}
		
		System.out.printf(OUTPUT_MESSAGE_FORMAT, outputMessage.toString());
	}
}

